package me.spring.cloud.components.starter.swagger.gateway.dynamic;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import me.spring.cloud.components.starter.swagger.gateway.properties.SwaggerProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Set;

/**
 * @description: 动态swagger文档
 * @author: luffy
 * @create: 2018-09-12 17:42
 **/
@Slf4j
@ConditionalOnProperty(name = SwaggerProperties.prefix + ".enable", havingValue = "true")
public class DynamicSwaggerDocumentConfiguration implements ApplicationContextAware {

  public final static String namespaces = "swagger-gateway";

  private ApplicationContext applicationContext;

  @ApolloConfigChangeListener(namespaces)
  private void onChange(ConfigChangeEvent changeEvent) {
    refreshProperties(changeEvent.changedKeys());
  }

  private void refreshProperties(Set<String> changedKeys) {
    log.info("Refreshing swagger doc: {}", changedKeys);
    this.applicationContext.publishEvent(new EnvironmentChangeEvent(changedKeys));
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }
}
